package com.hxzy.service.impl;

import com.hxzy.common.utils.StringUtils;
import com.hxzy.dto.RoleSearchDTO;
import com.hxzy.entity.Menu;
import com.hxzy.entity.Role;
import com.hxzy.mapper.RoleMapper;
import com.hxzy.service.MenuService;
import com.hxzy.service.RoleService;
import com.hxzy.vo.ZTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 类说明
 *
 * @author admin
 * @date 2021-09-06
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class RoleServiceImpl extends CommonServiceImpl<Role,Long> implements RoleService {

    private RoleMapper roleMapper;

    @Autowired
    private MenuService  menuService;

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
        super.setMyBatisBaseDao(roleMapper);
    }

    @Override
    public List<Role> search(RoleSearchDTO roleSearchDTO) {
        return this.roleMapper.search(roleSearchDTO);
    }

    /**
     * 根据角色查询拥的菜单id并且组装成一个ztree
     * @param roleId
     * @return
     */
    @Override
    public List<ZTree> roleMenuTreeData(Integer roleId) {
        List<ZTree> ztreeList=new ArrayList<>();
        //1、查询所有菜单
        List<Menu> allMenu = this.menuService.selectAllMenu();
        //2、查询该角色原先已分在数据库sys_role_menu根据role_id查询分配的menu_id菜单信息
        final List<Long>   ownerMenuList=new ArrayList<>();
        //3、修改判断
        if(roleId!=null && roleId>0){
            ownerMenuList.addAll(this.menuService.selectRoleOwnMenuId(roleId));
        }

        //4、组装根节点(parent_id==0)    ladbma表达式  1.8特性
        allMenu.stream().filter(p-> p.getParentId().equals(0L)).forEach( p-> {
            // 实例化一个Ztree
            ZTree   ztree=new ZTree();
            ztree.setId( p.getId());
            String perms="<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + (StringUtils.isBlank(p.getPerms())?"":p.getPerms()) + "</font>";
            ztree.setName(p.getName()+perms);
            // 判断之前是否分配过权限
            ztree.setChecked(ownerMenuList.contains(p.getId()));

            //加载后面的子节点
            loadChildrenMenu(ztree, allMenu, ownerMenuList);

            //添加到集合去
            ztreeList.add(ztree);
        });


        return ztreeList;
    }

    /**
     * 检查角色名称是否唯一
     * @param id
     * @param name
     * @return
     */
    @Override
    public int existsRoleName(Integer id, String name) {

        return this.roleMapper.existsRoleName(id,name);
    }

    /**
     * 检查角色标识是否唯一
     * @param id
     * @param perms
     * @return
     */
    @Override
    public int existsRolePerms(Integer id, String perms) {
        return this.roleMapper.existsRolePerms(id,perms);
    }


    @Override
    public int addAndGrantMenu(Role role, List<Long> permsList) {
        //1、新增
        int count=super.insert(role);
        if(count!=0){
            //2、分配了权限
            if(permsList!=null && permsList.size()>0){
                this.roleMapper.grantMenuPerms( role.getId(), permsList);
            }
        }
        return count;
    }

    /**
     * 修改并保存权限
     * @param role
     * @param permsList
     * @return
     */
    @Override
    public int editAndGrantMenu(Role role, List<Long> permsList) {
        //1、保存
        int count = super.updateByPrimaryKeySelective(role);
        if(count!=0){

            //2、先删除已有权限
            this.roleMapper.deleteMenuByRoleId(role.getId());

            //3、分配了权限
            if(permsList!=null && permsList.size()>0){
                this.roleMapper.grantMenuPerms( role.getId(), permsList);
            }
        }
        return count;
    }

    /**
     * 查询下级节点
     * @param parent   上级节点
     * @param allMenu  数据库所有菜单
     * @param ownerMenuList  该角色拥有的菜单id
     */
    private void loadChildrenMenu(ZTree  parent,List<Menu> allMenu ,List<Long>   ownerMenuList){
        //子节点有哪些
        List<ZTree>  childList=new ArrayList<>();

        //查询子节点
        allMenu.stream().filter(p-> p.getParentId().equals(parent.getId())).forEach(m->{
            // 实例化一个Ztree
            ZTree   ztree=new ZTree();
            ztree.setId( m.getId());
            String perms="<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + (StringUtils.isBlank(m.getPerms())?"":m.getPerms()) + "</font>";
            ztree.setName(m.getName()+perms);

            // 判断之前是否分配过权限
            ztree.setChecked(ownerMenuList.contains(m.getId()));

            //递归操作（方法内部调用自己的名称，不出现死循环）
            loadChildrenMenu(ztree,allMenu,ownerMenuList);

            //添加到子节点集合中
            childList.add(ztree);
        });


        //如果childList.size()>0  才说明 子节点
        if(childList.size()>0){
            parent.setChildren(childList);
        }

    }


}
